package cn.edu.swu.auth;


import jakarta.servlet.ServletConfig;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginServlet extends HttpServlet {

    private Map<String, User> users =  new HashMap<>();

public void init(ServletConfig config){
    String userString = config.getInitParameter("users");
    String[] items = userString.split(";");
    for (String item:items){
        String[] userAndPass = item.split("@");
        User user=new User(userAndPass[0],userAndPass[1]);
        this.users.put(user.getName(),user);
    }
    System.out.println("user data initialized!!");
}

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request,response);
    }

    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");

        User user= this.users.get(name);
        if (user!=null){
            if (user.getPass().equals(pass)){
                response.sendRedirect("./book/list");
                return;
            }
        }

response.sendRedirect("./index.html");
    }
}